/**
 * Yolema.com Inc.
 * Copyright (c) 2011-2012 All Rights Reserved.
 */
package org.grayrabbit.pay.core.model.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 序列化的工具类
 * 
 * @author wy
 * @version $Id: SerializableUtil.java, v 0.1 2012-6-2 下午10:08:26 wy Exp $
 */
public class SerializableUtil {

    // 二进制流的长度
    private static final int BYTE_ARRAY_LENGTH = 4000;
    
    /**
     * 序列化对象
     * @param object
     * @return
     * @throws IOException 
     */
    public static byte[] convertFromObj(Object object) throws IOException{
        byte[] byteArray = null;
        if (object == null) {
            return byteArray;
        }
        ByteArrayOutputStream byteOut = null;
        ObjectOutputStream objOut = null;
        try {
            byteOut = new ByteArrayOutputStream(BYTE_ARRAY_LENGTH);
            objOut = new ObjectOutputStream(byteOut);
            objOut.writeObject(object);
            objOut.flush();
            byteOut.flush();
            byteArray = byteOut.toByteArray();
        }
        finally {
            if (objOut != null) {
                objOut.close();
            }
            if (byteOut != null) {
                byteOut.close();
            }
        }
        return byteArray;
    }

    /**
     * 反序列化
     * @param byteArray
     * @return
     * @throws ClassNotFoundException 
     */
    public static Object convertToObj(byte[] byteArray) throws IOException, ClassNotFoundException {
        ObjectInputStream objInputStream = null;
        Object obj = null;
        try {
            objInputStream = new ObjectInputStream(new ByteArrayInputStream(byteArray));
            obj = objInputStream.readObject();
        } finally {
            if (objInputStream != null) {
                objInputStream.close();
            }
        }
        return obj;
    }

}
